package springcloud.study.eurekazuulclient.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * zuul 过滤器
 */
@Component
public class MyFilter extends ZuulFilter {


    /** 4种类型 pre post routing error*/
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /** 值越小 越早执行该过滤器 */
    @Override
    public int filterOrder() {
        return 0;
    }
    /** 如果为true执行run过滤逻辑*/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = context.getResponse();
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().length() == 0) {
            try {
                context.setResponseStatusCode(401);
                context.setSendZuulResponse(false);
                response.setContentType("text/html;charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("登录过期，请重新登录");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
